/*!
 * Copyright (C) 2020 - All Rights Reserved by
 * @author : ZhaoYanbo
 * @email  : zyb920@hotmail.com
 * @created: 2020-10-31
 * @version: 1.0.0.0
 *
 */

#include "CScan.h"
#include <QDir>
#include <QFileInfo>
#include <QPixmap>
#include <QPainter>
#include <QtDebug>

CScan::CScan(QObject *parent) : QThread(parent)
{
    m_filters << "*.png" << "*.jpg" << "*.jpeg";
}

CScan::~CScan()
{
    stop();
}

QStringList CScan::files() const
{
    return m_files;
}

void CScan::scan(const QString &dir)
{
    QStringList list;
    list << dir;

    scan(list);
}

void CScan::scan(const QStringList &dirs)
{
    std::lock_guard<std::mutex> guard(m_mutex);

    m_dirs.clear();
    m_dirs.append(dirs);

    this->start();
}

void CScan::run()
{
    std::lock_guard<std::mutex> guard(m_mutex);

    qDebug() << "scan dir:" << m_dirs;
    //循环扫描
    QStringList files;
    for(const QString &path : m_dirs) {
        //m_files << getFiles(path, m_filters);
        getFiles(path, m_filters, files);
    }
    m_dirs.clear();
    qDebug() << "scan end:" << files.length();

    m_files.clear();
    m_files.append(files);
}


QStringList CScan::getFiles(const QString &path, const QStringList &filters)
{
    QStringList list;

    if(this->isInterruptionRequested())
        return list;

    QDir dir;
    dir.setPath(path);
    QFileInfoList infolist = dir.entryInfoList(filters,
                                               QDir::AllDirs|QDir::Files|QDir::NoDotAndDotDot);

    foreach (const QFileInfo &info, infolist)
    {
        if(this->isInterruptionRequested())
            break;

        if(info.isDir())
            list << getFiles(dir.absolutePath() + "/" + info.fileName(), filters);
        else
            list << info.absoluteFilePath();
    }

    return list;
}

void CScan::getFiles(const QString &path, const QStringList &filters, QStringList &list)
{
    if(this->isInterruptionRequested())
        return;

    QDir dir;
    dir.setPath(path);
    QFileInfoList infolist = dir.entryInfoList(filters,
                                               QDir::AllDirs|QDir::Files|QDir::NoDotAndDotDot);

    foreach (const QFileInfo &info, infolist)
    {
        if(this->isInterruptionRequested())
            break;

        if(info.isDir())
            getFiles(dir.absolutePath() + "/" + info.fileName(), filters, list);
        else
            list << info.absoluteFilePath();
    }
}

void CScan::stop()
{
    if(this->isRunning()) {
        this->requestInterruption();
        wait();
    }
}

void CScan::clear()
{
    m_files.clear();
    m_dirs.clear();
}

int CScan::length() const
{
    return m_files.length();
}
